package com.gym.core.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gym.core.spring.SpringUtil;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-1-6 下午5:52:16
 */
public class AsyncThreadPoolUtils {
	private static final Logger logger = LoggerFactory.getLogger(AsyncThreadPoolUtils.class);

    //配置参数
    public  final int corePoolSize = 100;
    public  final int maxPoolSize = 400;
    public  final int maxQueueSize = 1000;
    //单位采用秒
    public  final int keepAliveTime = 60;

    //采用无界队列
    private  final ThreadPoolExecutor worker = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxQueueSize),
            new CallerRunsPolicy() {
                public void rejectedExecution(Runnable policy, ThreadPoolExecutor arg1) {
                	super.rejectedExecution(policy, arg1);
                	logger.warn("run in calling thread rejectedExecution");
                }                	    
            });

    
    private static AsyncThreadPoolUtils instance;
	public static AsyncThreadPoolUtils getInstance() {
		if(instance == null){
			instance = SpringUtil.getCtx().getBean(AsyncThreadPoolUtils.class);
		}
		return instance;
	}

    public  void execute(final Runnable runnable){
        worker.execute(runnable);
    }

    public  void shutdown(){
        if (worker != null) {
            worker.shutdownNow();
        }
    }

    //监控Executor
    public  long getCompletedTaskCount() {
        return worker.getCompletedTaskCount();
    }

    public  int getPoolSize(){
        return worker.getPoolSize();
    }

    public  int getActiveCount(){
    	return worker.getActiveCount();
    }

    public  int getMaximumPoolSize(){
        return worker.getMaximumPoolSize();
    }

    public  void setMaximumPoolSize(int size){
        worker.setMaximumPoolSize(size);
    }

    public  int getCorePoolSize(){
        return worker.getCorePoolSize();
    }

    public  void setCorePoolSize(int size){
        worker.setCorePoolSize(size);
    }

    public  int getQueueSize(){
        return worker.getQueue().size();
    }
    
    
    
}

